import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'

const STORE_KEY_TOKEN = 'ptms-token'
const STORE_KEY_USER  = 'ptms-user'
const CENTER_CAMPUS_ID = '1'
const DEFAULT_AVATAR = 'https://cube.elemecdn.com/3/7c/3ea6beec64369e630459aa77654b212c.png'

export const useAuthStore = defineStore('auth', () => {
    const router = useRouter()

    /* ---------- 状态 ---------- */
    const token = ref('')
    const user  = ref({})

    /* 初始读 localStorage */
    const initAuth = () => {
        const t = localStorage.getItem(STORE_KEY_TOKEN)
        const u = localStorage.getItem(STORE_KEY_USER)
        if (t && u) {
            try {
                token.value = t
                user.value  = { ...getDefaultUser(), ...JSON.parse(u) }
            } catch { clearAuth() }
        } else { clearAuth() }
    }

    const getDefaultUser = () => ({
        id: '', username: '', realName: '', userType: '', status: '正常',
        campus: { id: '', name: '未分配校区', address: '' }, isSuperAdmin: false,
        phone: '未绑定手机号', email: '未绑定邮箱', photo: DEFAULT_AVATAR, createTime: '未知时间'
    })

    /* ---------- 核心动作 ---------- */
    const clearAuth = () => {
        token.value = ''
        user.value  = getDefaultUser()
        localStorage.removeItem(STORE_KEY_TOKEN)
        localStorage.removeItem(STORE_KEY_USER)
        user.value = null
        if (router.currentRoute.value.path !== '/') router.replace('/')
    }

    const setAuth = (newToken, newUser) => {
        const t = typeof newToken === 'string' ? newToken.trim() : ''
        if (t.length < 30) throw new Error('无效 Token')
        if (typeof newUser !== 'object' || !newUser.id || !newUser.username || !newUser.userType) {
            throw new Error('用户信息缺失')
        }
        const u = { ...getDefaultUser(), ...newUser, id: String(newUser.id) }
        u.campus = { ...getDefaultUser().campus, ...newUser.campus, id: String(newUser.campus?.id || '') }
        u.isSuperAdmin = u.userType.toLowerCase() === 'admin' && u.campus.id === CENTER_CAMPUS_ID

        token.value = t
        user.value  = u
        localStorage.setItem(STORE_KEY_TOKEN, t)
        localStorage.setItem(STORE_KEY_USER, JSON.stringify(u))
    }

    /* ---------- 登出 ---------- */
    const logout = async () => {
        try {
            await ElMessageBox.confirm('确定退出登录吗？', '提示', { type: 'warning' })
        } catch {
            return
        }
        clearAuth()
        ElMessage.success('已退出登录')
        window.location.replace('/')
    }

    /* ---------- 计算属性 ---------- */
    const isLoggedIn   = computed(() => token.value.trim().length > 0 && !!user.value.id)
    const isSuperAdmin = computed(() => user.value.isSuperAdmin)

    /* 初始化 */
    initAuth()

    return { token, user, isLoggedIn, isSuperAdmin, setAuth, clearAuth, logout }
})